package com.pkk.components.mq.config;

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

/**
 * @description:
 * @author: peikunkun
 * @create: 2018-10-11 14:47
 **/
@Configuration
public class RabbitConfig {

  @Autowired
  private ConnectionFactory connectionFactory;


  /**
   * @Description: 消息序列化器
   * @Param: []
   * @return: org.springframework.amqp.support.converter.MessageConverter
   * @Author: peikunkun
   * @Date: 2019/4/19 0019 下午 6:36
   */
  @Bean
  public MessageConverter messageConverter() {
    return new Jackson2JsonMessageConverter();
  }


  /**
   * @Description: 发送消息的
   * @必须是prototype类型
   * @Param: []
   * @return: org.springframework.amqp.rabbit.core.RabbitTemplate
   * @Author: peikunkun
   * @Date: 2019/4/19 0019 下午 6:32
   */
  @Bean
  @Primary
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public RabbitTemplate rabbitTemplate(MessageConverter messageConverter) {
    RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    rabbitTemplate.setMessageConverter(messageConverter);
    return rabbitTemplate;
  }

  /**
   * @Description: 这个指定的是配置监听的消息的消息序列化信息
   * @Param: [connectionFactory]
   * @return: org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory
   * @Author: peikunkun
   * @Date: 2019/4/19 0019 下午 6:31
   */
  @Bean
  public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setMessageConverter(messageConverter());
    //手动确认模式
    // 【AcknowledgeMode.NONE：自动确认
    //AcknowledgeMode.AUTO：根据情况确认
    //AcknowledgeMode.MANUAL：手动确认】
    //factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
    return factory;
  }

}
